<template>
  <el-card class="message-sender" shadow="hover">
    <template #header>
      <div class="card-header">
        <el-icon class="header-icon">
          <Message />
        </el-icon>
        <span class="header-title">消息发送</span>
        <el-tag v-if="selectedTopic" type="success" size="small">
          {{ selectedTopic.name }}
        </el-tag>
      </div>
    </template>

    <el-form 
      :model="form" 
      :rules="rules" 
      ref="formRef"
      label-width="100px"
      size="default"
    >
      <!-- Topic选择 -->
      <el-form-item label="目标Topic" prop="topic">
        <el-select
          v-model="form.topic"
          placeholder="选择Topic"
          style="width: 100%"
          filterable
          clearable
          @change="onTopicChange"
        >
          <el-option
            v-for="topic in topics"
            :key="topic.name"
            :label="topic.name"
            :value="topic.name"
          >
            <span style="float: left">{{ topic.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 12px">
              {{ topic.partition_count }}个分区
            </span>
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 消息内容 -->
      <el-form-item label="消息内容" prop="value">
        <el-input
          v-model="form.value"
          type="textarea"
          :rows="8"
          placeholder="请输入消息内容，支持JSON格式"
          show-word-limit
          :maxlength="10000"
        />
        <div class="message-tools">
          <el-button-group>
            <el-button 
              size="small" 
              @click="formatJson"
              :icon="DocumentCopy"
            >
              格式化JSON
            </el-button>
            <el-button 
              size="small" 
              @click="generateSampleMessage"
              :icon="Plus"
            >
              生成示例
            </el-button>
            <el-button 
              size="small" 
              @click="clearMessage"
              :icon="Delete"
            >
              清空
            </el-button>
          </el-button-group>
        </div>
      </el-form-item>

      <!-- 高级选项 -->
      <el-collapse v-model="advancedCollapse" class="advanced-options">
        <el-collapse-item title="高级选项" name="advanced">
          <el-row :gutter="20">
            <!-- 消息Key -->
            <el-col :span="8">
              <el-form-item label="消息Key" prop="key">
                <el-input
                  v-model="form.key"
                  placeholder="可选，用于分区路由"
                />
              </el-form-item>
            </el-col>

            <!-- 指定分区 -->
            <el-col :span="8">
              <el-form-item label="指定分区" prop="partition">
                <el-select
                  v-model="form.partition"
                  placeholder="自动选择"
                  clearable
                  style="width: 100%"
                >
                  <el-option
                    v-for="i in currentTopicPartitions"
                    :key="i"
                    :label="`分区 ${i}`"
                    :value="i"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <!-- 消息头 -->
            <el-col :span="8">
              <el-form-item label="消息头">
                <el-button 
                  size="small" 
                  @click="showHeadersDialog"
                  :icon="Setting"
                >
                  设置消息头
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-collapse>

      <!-- 发送按钮 -->
      <el-form-item style="margin-top: 20px;">
        <el-button-group>
          <el-button
            type="primary"
            :loading="sending"
            @click="sendSingleMessage"
            :disabled="!form.topic || !form.value"
            size="large"
          >
            <el-icon><Promotion /></el-icon>
            发送消息
          </el-button>
          
          <el-button
            type="success"
            :loading="batchSending"
            @click="showBatchDialog"
            :disabled="!form.topic"
            size="large"
          >
            <el-icon><DataBoard /></el-icon>
            批量发送
          </el-button>
        </el-button-group>
      </el-form-item>
    </el-form>

    <!-- 消息头设置对话框 -->
    <el-dialog
      v-model="headersDialogVisible"
      title="设置消息头"
      width="60%"
      :close-on-click-modal="false"
    >
      <div class="headers-container">
        <div
          v-for="(header, index) in messageHeaders"
          :key="index"
          class="header-row"
        >
          <el-input
            v-model="header.key"
            placeholder="Header Key"
            style="width: 40%"
          />
          <el-input
            v-model="header.value"
            placeholder="Header Value"
            style="width: 40%; margin-left: 10px"
          />
          <el-button
            type="danger"
            :icon="Delete"
            size="small"
            @click="removeHeader(index)"
            style="margin-left: 10px"
          />
        </div>
        
        <el-button
          type="primary"
          :icon="Plus"
          size="small"
          @click="addHeader"
          style="margin-top: 10px"
        >
          添加消息头
        </el-button>
      </div>

      <template #footer>
        <el-button @click="headersDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveHeaders">保存</el-button>
      </template>
    </el-dialog>

    <!-- 批量发送对话框 -->
    <el-dialog
      v-model="batchDialogVisible"
      title="批量发送消息"
      width="70%"
      :close-on-click-modal="false"
    >
      <div class="batch-container">
        <el-alert
          title="批量发送说明"
          description="每行一条消息，支持JSON格式。可以使用 key:value 的格式指定消息Key。"
          type="info"
          :closable="false"
          style="margin-bottom: 16px"
        />
        
        <el-input
          v-model="batchMessages"
          type="textarea"
          :rows="10"
          placeholder="请输入批量消息，每行一条消息"
          show-word-limit
          :maxlength="50000"
        />
        
        <div class="batch-info">
          <span>消息数量: {{ batchMessageCount }}</span>
          <el-button
            type="primary"
            :loading="batchSending"
            @click="sendBatchMessages"
            :disabled="!batchMessages.trim()"
            style="margin-left: 16px"
          >
            发送批量消息
          </el-button>
        </div>
      </div>

      <template #footer>
        <el-button @click="batchDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script>
import { ref, reactive, computed, watch } from 'vue'
import { useKafkaStore } from '@/stores/kafka'
import { ElMessage, ElNotification } from 'element-plus'
import { 
  Message, DocumentCopy, Plus, Delete, Setting, 
  Promotion, DataBoard 
} from '@element-plus/icons-vue'

export default {
  name: 'MessageSender',
  components: {
    Message, DocumentCopy, Plus, Delete, Setting, 
    Promotion, DataBoard
  },
  props: {
    selectedTopic: {
      type: Object,
      default: null
    },
    topics: {
      type: Array,
      default: () => []
    }
  },
  emits: ['message-sent'],
  setup(props, { emit }) {
    const kafkaStore = useKafkaStore()
    const formRef = ref()
    
    // 表单数据
    const form = reactive({
      topic: '',
      value: '',
      key: '',
      partition: null,
      headers: {}
    })
    
    // 状态
    const sending = ref(false)
    const batchSending = ref(false)
    const advancedCollapse = ref([])
    
    // 对话框
    const headersDialogVisible = ref(false)
    const batchDialogVisible = ref(false)
    
    // 消息头
    const messageHeaders = ref([])
    
    // 批量发送
    const batchMessages = ref('')
    
    // 表单验证规则
    const rules = {
      topic: [
        { required: true, message: '请选择Topic', trigger: 'change' }
      ],
      value: [
        { required: true, message: '请输入消息内容', trigger: 'blur' }
      ]
    }
    
    // 计算属性
    const currentTopicPartitions = computed(() => {
      if (!props.selectedTopic) return 0
      return props.selectedTopic.partition_count
    })
    
    const batchMessageCount = computed(() => {
      if (!batchMessages.value.trim()) return 0
      return batchMessages.value.trim().split('\n').length
    })
    
    // 监听选中的Topic变化
    watch(() => props.selectedTopic, (newTopic) => {
      if (newTopic) {
        form.topic = newTopic.name
        form.partition = null // 重置分区选择
      }
    }, { immediate: true })
    
    // 方法
    const onTopicChange = (topicName) => {
      const topic = props.topics.find(t => t.name === topicName)
      if (topic) {
        form.partition = null // 重置分区选择
      }
    }
    
    const formatJson = () => {
      try {
        if (form.value.trim()) {
          const parsed = JSON.parse(form.value)
          form.value = JSON.stringify(parsed, null, 2)
          ElMessage.success('JSON格式化成功')
        }
      } catch (error) {
        ElMessage.error('JSON格式错误，无法格式化')
      }
    }
    
    const generateSampleMessage = () => {
      const sampleMessage = {
        timestamp: new Date().toISOString(),
        userId: 'user-' + Math.random().toString(36).substr(2, 9),
        message: 'Hello Kafka!',
        data: {
          type: 'sample',
          version: '1.0',
          payload: {
            content: 'This is a sample message',
            metadata: {
              source: 'kafka-monitor',
              priority: 'normal'
            }
          }
        }
      }
      
      form.value = JSON.stringify(sampleMessage, null, 2)
      ElMessage.success('已生成示例消息')
    }
    
    const clearMessage = () => {
      form.value = ''
      form.key = ''
      form.partition = null
      messageHeaders.value = []
      form.headers = {}
      ElMessage.success('消息内容已清空')
    }
    
    const addHeader = () => {
      messageHeaders.value.push({ key: '', value: '' })
    }
    
    const removeHeader = (index) => {
      messageHeaders.value.splice(index, 1)
    }
    
    const showHeadersDialog = () => {
      // 从form.headers初始化messageHeaders
      messageHeaders.value = Object.entries(form.headers).map(([key, value]) => ({
        key,
        value
      }))
      headersDialogVisible.value = true
    }
    
    const saveHeaders = () => {
      // 将messageHeaders保存到form.headers
      form.headers = {}
      messageHeaders.value.forEach(header => {
        if (header.key && header.value) {
          form.headers[header.key] = header.value
        }
      })
      headersDialogVisible.value = false
      ElMessage.success('消息头设置成功')
    }
    
    const showBatchDialog = () => {
      batchDialogVisible.value = true
    }
    
    const sendSingleMessage = async () => {
      if (!await validateForm()) return
      
      sending.value = true
      
      try {
        const messageRequest = {
          topic: form.topic,
          value: form.value,
          key: form.key || null,
          partition: form.partition,
          headers: Object.keys(form.headers).length > 0 ? form.headers : null
        }
        
        const response = await kafkaStore.sendMessage(messageRequest)
        
        if (response.success) {
          ElMessage.success('消息发送成功')
          ElNotification({
            title: '消息发送成功',
            message: `Topic: ${form.topic}\n分区: ${response.data.partition}\n偏移量: ${response.data.offset}`,
            type: 'success'
          })
          
          emit('message-sent', response.data)
          
          // 可选：清空表单
          // clearMessage()
        }
      } catch (error) {
        ElMessage.error(error.message || '消息发送失败')
        ElNotification({
          title: '消息发送失败',
          message: error.message || '发生未知错误',
          type: 'error'
        })
      } finally {
        sending.value = false
      }
    }
    
    const sendBatchMessages = async () => {
      if (!batchMessages.value.trim()) {
        ElMessage.warning('请输入批量消息')
        return
      }
      
      batchSending.value = true
      
      try {
        const messages = batchMessages.value.trim().split('\n').map(line => {
          const trimmedLine = line.trim()
          if (!trimmedLine) return null
          
          // 检查是否有key:value格式
          const keyValueMatch = trimmedLine.match(/^([^:]+):\s*(.+)$/)
          if (keyValueMatch) {
            return {
              key: keyValueMatch[1].trim(),
              value: keyValueMatch[2].trim()
            }
          } else {
            return {
              value: trimmedLine
            }
          }
        }).filter(msg => msg !== null)
        
        const batchRequest = {
          topic: form.topic,
          messages: messages
        }
        
        const response = await kafkaStore.sendBatchMessages(batchRequest)
        
        if (response.success) {
          const successCount = response.data.filter(r => r.success).length
          const totalCount = response.data.length
          
          ElMessage.success(`批量发送完成: ${successCount}/${totalCount} 成功`)
          ElNotification({
            title: '批量发送完成',
            message: `成功发送 ${successCount} 条消息，共 ${totalCount} 条`,
            type: successCount === totalCount ? 'success' : 'warning'
          })
          
          emit('message-sent', response.data)
          
          // 清空批量消息
          batchMessages.value = ''
          batchDialogVisible.value = false
        }
      } catch (error) {
        ElMessage.error(error.message || '批量发送失败')
        ElNotification({
          title: '批量发送失败',
          message: error.message || '发生未知错误',
          type: 'error'
        })
      } finally {
        batchSending.value = false
      }
    }
    
    const validateForm = async () => {
      try {
        await formRef.value.validate()
        return true
      } catch (error) {
        ElMessage.warning('请检查表单填写')
        return false
      }
    }
    
    return {
      form,
      formRef,
      rules,
      sending,
      batchSending,
      advancedCollapse,
      headersDialogVisible,
      batchDialogVisible,
      messageHeaders,
      batchMessages,
      currentTopicPartitions,
      batchMessageCount,
      onTopicChange,
      formatJson,
      generateSampleMessage,
      clearMessage,
      addHeader,
      removeHeader,
      showHeadersDialog,
      saveHeaders,
      showBatchDialog,
      sendSingleMessage,
      sendBatchMessages
    }
  }
}
</script>

<style scoped>
.message-sender {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-icon {
  margin-right: 8px;
  color: #409eff;
}

.header-title {
  font-weight: 600;
  flex: 1;
}

.message-tools {
  margin-top: 8px;
  display: flex;
  justify-content: flex-end;
}

.advanced-options {
  margin-bottom: 16px;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-button-group {
  display: flex;
  gap: 8px;
}

.headers-container {
  min-height: 200px;
}

.header-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.batch-container {
  min-height: 300px;
}

.batch-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
  font-size: 14px;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-row {
    flex-direction: column;
    gap: 8px;
  }
  
  .header-row .el-input {
    width: 100% !important;
    margin-left: 0 !important;
  }
  
  .batch-info {
    flex-direction: column;
    gap: 12px;
  }
}
</style> 